package com.hzh.cusviewdemo.Fragment;

import static com.hzh.cusviewdemo.Activity.MusicActivity.ACTION_UPDATE_UI_MUSIC;
import static com.hzh.cusviewdemo.Music.PlayerManagerReceiver.status;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.bumptech.glide.Glide;
import com.cbman.roundimageview.RoundImageView;
import com.hzh.cusviewdemo.Activity.LookCommentActivity;
import com.hzh.cusviewdemo.Activity.MusicActivity;
import com.hzh.cusviewdemo.Adapter.PlayListAdapter;
import com.hzh.cusviewdemo.Bean.MyMusicData;
import com.hzh.cusviewdemo.Bean.MySongMenu;
import com.hzh.cusviewdemo.Music.Constant;
import com.hzh.cusviewdemo.Music.MusicPlayService;
import com.hzh.cusviewdemo.Music.MyMusicUtil;
import com.hzh.cusviewdemo.Music.PlayerManagerReceiver;
import com.hzh.cusviewdemo.Presenter.MusicSongData;
import com.hzh.cusviewdemo.R;
import com.hzh.cusviewdemo.Ui.AlbumCoverView;
import com.hzh.cusviewdemo.Ui.MediaPlayView;
import com.hzh.cusviewdemo.Util.Config;
import com.hzh.cusviewdemo.Util.ImageDownloader;
import com.hzh.cusviewdemo.Util.ScreenUtils;
import com.hzh.cusviewdemo.Util.SugarUtils;
import com.hzh.cusviewdemo.Util.TimeUtils;
import com.kongzue.dialogx.dialogs.BottomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.suke.widget.SwitchButton;

import java.util.List;

import me.wcy.lrcview.LrcView;

public class PlayMusicFragment extends Fragment implements View.OnClickListener, LrcView.OnPlayClickListener {

    private LinearLayout fpm_linear;
    private ImageView fpm_back;
    private LrcView fpm_lrcView;
    private TextView fpm_title;
    private TextView fpm_songer;
    private SeekBar fpm_progress;
    private TextView fpm_current_time;
    private TextView fpm_total_time;
    private ImageView fpm_play;
    private ImageView fpm_next;
    private ImageView fpm_prev;
    private ImageView fpm_list;
    private ImageView fpm_mode;
    private TextView fpm_look_comment;
    private ImageView fpm_like;

    private RoundImageView flp_cover_pic;
    private TextView flp_songname;
    private MediaPlayView flp_play_view;
    private AlbumCoverView flp_cover_view;
    private SwitchButton flp_switch_look_lrc;
    private TextView flp_reduce_size;
    private TextView flp_current_size;
    private TextView flp_add_size;

    private String lrcContent = ""; // lrc
    private PlayReceiver mReceiver;
    private UpdateReceiver updateReceiver;
    private boolean isDraggingProgress;
    private PlayListAdapter playlistAdapter;

    private float currentShowSize = ConvertUtils.sp2px(20f);  // 12 ~ 28
    private float normalShowSize = ConvertUtils.sp2px(15f);

    private boolean isStartPlayMusic = false;

    public PlayMusicFragment(Boolean isPlayMusic) {
        this.isStartPlayMusic = isPlayMusic;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_play_music, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();

        // 获取播放模式
        loadPlayMode();

        // 注册接收广播
        register();
        registerUpdateReceiver();

        initData();
    }

    private void register() {
        // 执行
        Log.e(Config.TAG, "PMF：register");
        mReceiver = new PlayReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_UPDATE_UI_MUSIC);
        requireActivity().registerReceiver(mReceiver, intentFilter);
    }

    private void initView() {

        fpm_linear = requireActivity().findViewById(R.id.fpm_linear);
        fpm_back = requireActivity().findViewById(R.id.fpm_back);
        fpm_title = requireActivity().findViewById(R.id.fpm_title);
        fpm_songer = requireActivity().findViewById(R.id.fpm_songer);
        fpm_progress = requireActivity().findViewById(R.id.fpm_progress);
        fpm_current_time = requireActivity().findViewById(R.id.fpm_current_time);
        fpm_total_time = requireActivity().findViewById(R.id.fpm_total_time);
        fpm_play = requireActivity().findViewById(R.id.fpm_play);
        fpm_next = requireActivity().findViewById(R.id.fpm_next);
        fpm_prev = requireActivity().findViewById(R.id.fpm_prev);
        fpm_list = requireActivity().findViewById(R.id.fpm_list);
        fpm_mode = requireActivity().findViewById(R.id.fpm_mode);
        fpm_look_comment = requireActivity().findViewById(R.id.fpm_look_comment);
        fpm_like = requireActivity().findViewById(R.id.fpm_like);
        flp_cover_pic = requireActivity().findViewById(R.id.flp_cover_pic);
        flp_songname = requireActivity().findViewById(R.id.flp_songname);
        flp_play_view = requireActivity().findViewById(R.id.flp_play_view);
        flp_switch_look_lrc = requireActivity().findViewById(R.id.flp_switch_look_lrc);
        flp_reduce_size = requireActivity().findViewById(R.id.flp_reduce_size);
        flp_current_size = requireActivity().findViewById(R.id.flp_current_size);
        flp_add_size = requireActivity().findViewById(R.id.flp_add_size);
        int screenWidth = com.blankj.utilcode.util.ScreenUtils.getScreenWidth();
        flp_play_view.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, screenWidth));

        if (!MyMusicUtil.getStringShared(Constant.KEY_PIC).equalsIgnoreCase("")) {
            ImageDownloader.downloadImageAsync(MyMusicUtil.getStringShared(Constant.KEY_PIC), bitmap -> {
                if (!ObjectUtils.isEmpty(bitmap)) {
                    flp_play_view.setPlayPic(bitmap);
                } else {
                    flp_play_view.setPlayPic(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo));
                }
            });
        }
        if (isStartPlayMusic) {
            flp_play_view.play();
        }

        flp_switch_look_lrc.setOnCheckedChangeListener((view, isChecked) -> {
            if (isChecked) {
                flp_play_view.setVisibility(View.GONE);
            } else {
                flp_play_view.setVisibility(View.VISIBLE);
            }
        });

        // 设置歌名歌手
        if (ObjectUtils.isNotEmpty(MyMusicUtil.getStringShared(Constant.KEY_NAME))) {
            flp_songname.setText(MyMusicUtil.getStringShared(Constant.KEY_NAME) + " - " + MyMusicUtil.getStringShared(Constant.KEY_SONGER));
        }
        if (ObjectUtils.isNotEmpty(MyMusicUtil.getStringShared(Constant.KEY_PIC))) {
            Glide.with(requireActivity()).load(MyMusicUtil.getStringShared(Constant.KEY_PIC)).placeholder(R.drawable.ic_logo).error(R.drawable.ic_logo).into(flp_cover_pic);
        }

        Log.e(Config.TAG, "第一次进入播放页，musicDataByRid -- > " + MyMusicUtil.getStringShared(Constant.KEY_ID));
        MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(MyMusicUtil.getStringShared(Constant.KEY_ID));
        if (musicDataByRid != null) {
            Log.e(Config.TAG, "第一次进入播放页，数据 -- > " + musicDataByRid);
            if (musicDataByRid.getMenu().equals("我喜欢的音乐")) {
                fpm_like.setImageResource(R.drawable.ic_like_fill);
            } else {
                fpm_like.setImageResource(R.drawable.ic_like_normal);
            }
        }

        fpm_lrcView = requireActivity().findViewById(R.id.fpm_lrcView);
        fpm_lrcView.setDraggable(false, this);
        fpm_lrcView.setCurrentTextSize(currentShowSize);  // 正在唱的歌词大小
        fpm_lrcView.setNormalTextSize(normalShowSize);  // 其他的歌词大小
        flp_current_size.setText(ConvertUtils.px2sp(currentShowSize) + "");
        if (!MyMusicUtil.getStringShared(Constant.KEY_LRC_LIST).equals("")) {
            fpm_lrcView.loadLrc(MyMusicUtil.getStringShared(Constant.KEY_LRC_LIST));
        }

        fpm_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (seekBar == fpm_progress) {
                    if (isDraggingProgress) {
                        // 拖动进度
                        Log.e(Config.TAG, "drag time： " + progress * 1000);
                        // Log.e(Config.TAG, "PMF:进度改变");
                        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PROGRESS);
                        intent.putExtra(Constant.KEY_CURRENT, progress * 1000);
                        requireActivity().sendBroadcast(intent);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.e(Config.TAG, "PMF:onStartTrackingTouch");
                isDraggingProgress = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.e(Config.TAG, "PMF:onStopTrackingTouch");
                isDraggingProgress = false;
            }
        });

        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int top = ScreenUtils.getStatusBarHeight(requireActivity());
            fpm_linear.setPadding(0, top, 0, 0);
        }

        fpm_back.setOnClickListener(this);
        fpm_play.setOnClickListener(this);
        fpm_next.setOnClickListener(this);
        fpm_prev.setOnClickListener(this);
        fpm_mode.setOnClickListener(this);
        fpm_list.setOnClickListener(this);
        flp_reduce_size.setOnClickListener(this);
        flp_add_size.setOnClickListener(this);
        fpm_list.setOnClickListener(this);
        fpm_look_comment.setOnClickListener(this);
        fpm_like.setOnClickListener(this);

    }

    private void initData() {
        playOrChangeMusic(MyMusicUtil.getStringShared(Constant.KEY_PATH));
    }

    /**
     * play or change music
     */
    private void playOrChangeMusic(String musicPath) {
        if (musicPath == null) {
            return;
        }
        // 一些处理
        fpm_title.setText(MyMusicUtil.getStringShared(Constant.KEY_NAME));
        fpm_songer.setText(MyMusicUtil.getStringShared(Constant.KEY_SONGER));

        lrcContent = MyMusicUtil.getStringShared(Constant.KEY_LRC_LIST);
        setLrcList(lrcContent);
    }


    public void reloadLrc() {
        lrcContent = MyMusicUtil.getStringShared(Constant.KEY_LRC_LIST);
        Log.e(Config.TAG, "播放音乐 - reloadLrc 是否有歌词 -> " + (lrcContent == null || lrcContent.isEmpty()));
//        setLrcList(lrcContent);
    }

    @Override
    public void onResume() {
        super.onResume();
        lrcContent = MyMusicUtil.getStringShared(Constant.KEY_LRC_LIST);
        Log.e(Config.TAG, "播放音乐 - onResume 是否有歌词 -> " + (lrcContent == null || lrcContent.isEmpty()));
//        setLrcList(lrcContent);
    }

    private void setLrcList(String content) {
        if (fpm_lrcView != null) {
            fpm_lrcView.loadLrc(content);
        }
    }

    private void loadPlayMode() {
        // 加载当前模式
        int playMode = MyMusicUtil.getIntShared(Constant.KEY_MODE);
        Log.e(Config.TAG, "切换后playMode:" + playMode);
        fpm_mode.setImageLevel(playMode);
    }

    @Override
    public void onClick(View view) {
        if (view == fpm_back) {
            requireActivity().onBackPressed();
        } else if (view == fpm_play) {
            if (MyMusicUtil.getStringShared(Constant.KEY_ID).isEmpty()) {
                return;
            }
//            showPlayStatus();
            //如果当前媒体在播放音乐状态，则图片显示暂停图片，按下播放键，则发送暂停媒体命令，图片显示播放图片。以此类推。
            if (status == Constant.STATUS_PAUSE) {

                // 最原始代码
//                Log.e(Config.TAG, "status == Constant.STATUS_PAUSE\nPATH：" + MyMusicUtil.getStringShared(Constant.KEY_PATH));
//                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
//                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
//                intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
//                requireActivity().sendBroadcast(intent);

                // 二次改动代码
//                MyMusicData musicDataByRid = SugarUtils.findMusicDataByRid(MyMusicUtil.getStringShared(Constant.KEY_ID));
//                Log.e(Config.TAG, "status == Constant.STATUS_PAUSE\nPATH：" + MyMusicUtil.getStringShared(Constant.KEY_PATH));
//                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
//                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
//                intent.putExtra(Constant.KEY_PATH, musicDataByRid.getUrl());
//                intent.putExtra(Constant.KEY_ID, MyMusicUtil.getStringShared(Constant.KEY_ID));
//                intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
//                requireActivity().sendBroadcast(intent);

                /*if (MyMusicUtil.getStringShared(Constant.IS_PLAYING_MUSIC).equals("0")) {
                    // 未在播放音乐
                    MyMusicData musicDataByRid = SugarUtils.findMusicDataByRid(MyMusicUtil.getStringShared(Constant.KEY_ID));
                    Log.e(Config.TAG, "status == Constant.STATUS_PAUSE\nPATH：" + MyMusicUtil.getStringShared(Constant.KEY_PATH));
                    Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                    intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                    intent.putExtra(Constant.KEY_PATH, musicDataByRid.getUrl());
                    intent.putExtra(Constant.KEY_ID, MyMusicUtil.getStringShared(Constant.KEY_ID));
                    intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
                    requireActivity().sendBroadcast(intent);
                    MyMusicUtil.setShared(Constant.IS_PLAYING_MUSIC, "1");
                } else {
                    Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                    intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                    intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
                    requireActivity().sendBroadcast(intent);
                }*/

                MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(MyMusicUtil.getStringShared(Constant.KEY_ID));
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                intent.putExtra(Constant.KEY_PATH, musicDataByRid.getUrl());
                intent.putExtra(Constant.KEY_ID, MyMusicUtil.getStringShared(Constant.KEY_ID));
                intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
                requireActivity().sendBroadcast(intent);

            } else if (status == Constant.STATUS_PLAY) {
                Log.e(Config.TAG, "status == Constant.STATUS_PLAY");
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PAUSE);
                requireActivity().sendBroadcast(intent);
            } else {
                Log.e(Config.TAG, "other status == " + status);
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                intent.putExtra(Constant.KEY_PATH, MyMusicUtil.getStringShared(Constant.KEY_PATH));
                requireActivity().sendBroadcast(intent);
            }
        } else if (view == fpm_next) {
            if (MyMusicUtil.getStringShared(Constant.KEY_ID).isEmpty()) {
                // 当前无song
                return;
            }
            MyMusicUtil.playClickNextMusic(requireActivity());
        } else if (view == fpm_prev) {
            // 上一首
            if (MyMusicUtil.getStringShared(Constant.KEY_ID).isEmpty()) {
                // 当前无song
                return;
            }
            MyMusicUtil.playPreMusic(requireActivity());
        } else if (view == fpm_mode) {
            // 切换播放模式
            int playMode = MyMusicUtil.getIntShared(Constant.KEY_MODE);
            Log.e(Config.TAG, "切换前playMode:" + playMode);
            switch (playMode) {
                case Constant.PLAYMODE_SEQUENCE:
                    MyMusicUtil.setShared(Constant.KEY_MODE, Constant.PLAYMODE_SINGLE_REPEAT);
                    break;
                case Constant.PLAYMODE_SINGLE_REPEAT:
                    MyMusicUtil.setShared(Constant.KEY_MODE, Constant.PLAYMODE_RANDOM);
                    break;
                case Constant.PLAYMODE_RANDOM:
                    MyMusicUtil.setShared(Constant.KEY_MODE, Constant.PLAYMODE_SEQUENCE);
                    break;
            }
            loadPlayMode();
        } else if (view == fpm_list) {
            // 显示播放列表
            showPlayList();
        } else if (view == fpm_look_comment) {
            // 显示播放列表
            lookMusicComment();
        } else if (view == flp_reduce_size) {
            // 减小歌词大小
            if (ConvertUtils.px2sp(currentShowSize) <= 14) {
                return;
            }
            currentShowSize = currentShowSize - ConvertUtils.sp2px(1);
            normalShowSize = normalShowSize - ConvertUtils.sp2px(1);
            fpm_lrcView.setCurrentTextSize(currentShowSize);
            fpm_lrcView.setNormalTextSize(normalShowSize);
            fpm_lrcView.invalidate();
            flp_current_size.setText(ConvertUtils.px2sp(currentShowSize) + "");
        } else if (view == flp_add_size) {
            // 加大歌词大小
            if (ConvertUtils.px2sp(currentShowSize) >= 28) {
                return;
            }
            currentShowSize = currentShowSize + ConvertUtils.sp2px(1);
            normalShowSize = normalShowSize + ConvertUtils.sp2px(1);
            fpm_lrcView.setCurrentTextSize(currentShowSize);
            fpm_lrcView.setNormalTextSize(normalShowSize);
            fpm_lrcView.invalidate();
            flp_current_size.setText(ConvertUtils.px2sp(currentShowSize) + "");
        } else if (view == fpm_like) {
            // 把歌曲添加到我喜欢
            String musicId = MyMusicUtil.getStringShared(Constant.KEY_ID);
            Log.e(Config.TAG, "播放音乐 - 歌曲ID -> " + musicId);
            MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(musicId);
            if (musicDataByRid != null) {
                if (musicDataByRid.getMenu().equals("我喜欢的音乐")) {
                    // 已经喜欢过该歌曲
                    // 更新到我喜欢
                    musicDataByRid.setMenu("全部歌曲");
                    musicDataByRid.save();

                    MySongMenu menu = SugarUtils.getSongMenuByName("我喜欢的音乐");
                    if (menu != null) {
                        menu.setNum(menu.getNum() - 1);
                        List<MyMusicData> likeMusicDataList = SugarUtils.findMusicDataByMenu("我喜欢的音乐");
                        if (!likeMusicDataList.isEmpty()) {
                            menu.setPic(likeMusicDataList.get(0).getPic());
                        } else {
                            menu.setPic("");
                        }
                        menu.save();
                    }

                    MySongMenu allMenu = SugarUtils.getSongMenuByName("全部歌曲");
                    if (allMenu != null) {
                        allMenu.setNum(allMenu.getNum() + 1);
                        allMenu.setPic(MyMusicUtil.getStringShared(Constant.KEY_PIC));
                        allMenu.save();
                    }

                    // 置红色
                    fpm_like.setImageResource(R.drawable.ic_like_normal);

                    // 通知首页刷新
                    Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
                    musicIntent.putExtra(Constant.STATUS, Constant.STATUS_UPDATE_MENU_LIST);
                    requireActivity().sendBroadcast(musicIntent);
                } else {
                    // 更新到我喜欢
                    musicDataByRid.setMenu("我喜欢的音乐");
                    musicDataByRid.save();

                    MySongMenu menu = SugarUtils.getSongMenuByName("我喜欢的音乐");
                    if (menu != null) {
                        menu.setNum(menu.getNum() + 1);
                        menu.setPic(MyMusicUtil.getStringShared(Constant.KEY_PIC));
                        menu.save();
                    }

                    MySongMenu allMenu = SugarUtils.getSongMenuByName("全部歌曲");
                    if (allMenu != null) {
                        allMenu.setNum(allMenu.getNum() - 1);
                        List<MyMusicData> unLikeMusicDataList = SugarUtils.findMusicDataByMenu("全部歌曲");
                        if (!unLikeMusicDataList.isEmpty()) {
                            allMenu.setPic(unLikeMusicDataList.get(0).getPic());
                        } else {
                            allMenu.setPic("");
                        }
                        allMenu.save();
                    }

                    // 置红色
                    fpm_like.setImageResource(R.drawable.ic_like_fill);

                    // 通知首页刷新
                    Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
                    musicIntent.putExtra(Constant.STATUS, Constant.STATUS_UPDATE_MENU_LIST);
                    requireActivity().sendBroadcast(musicIntent);
                }
            }

            Intent updateUiIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
            updateUiIntent.putExtra(Constant.STATUS, Constant.STATUS_REFRESH_LIKE_FROM_PLAY_PAGE);
            requireActivity().sendBroadcast(updateUiIntent);
        }
    }

    /**
     * 跳转到
     */
    private void lookMusicComment() {
        Intent intent = new Intent(requireActivity(), LookCommentActivity.class);
        intent.putExtra("TAG_MUSIC_ID", MyMusicUtil.getStringShared(Constant.KEY_ID));
        startActivity(intent);
    }

    /**
     * 显示播放列表
     */
    public void showPlayList() {
        BottomDialog.build().setTitle("播放列表").setCustomView(new OnBindView<BottomDialog>(R.layout.dialog_play_list) {
            @Override
            public void onBind(BottomDialog dialog, View layout) {
                RecyclerView dpl_list = layout.findViewById(R.id.dpl_list);
                // 渲染数据
                dpl_list.setLayoutManager(new LinearLayoutManager(requireActivity()));
                playlistAdapter = new PlayListAdapter(SugarUtils.findMusicData(), requireActivity());
                dpl_list.setAdapter(playlistAdapter);
            }
        }).show();
    }

    private void registerUpdateReceiver() {
        try {
            if (updateReceiver != null) {
                this.unRegisterUpdateReceiver();
            }
            updateReceiver = new UpdateReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(PlayerManagerReceiver.ACTION_UPDATE_UI_ADAPTER);
            requireActivity().registerReceiver(updateReceiver, intentFilter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unRegisterUpdateReceiver() {
        try {
            if (updateReceiver != null) {
                requireActivity().unregisterReceiver(updateReceiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class UpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 通知列表刷新
            if (playlistAdapter != null) {
                playlistAdapter.notifyDataSetChanged();
            }
        }
    }

    class PlayReceiver extends BroadcastReceiver {

        int status;
        int duration;
        int current;
        String currentSentence;
        String coverPic; // 封面图片

        @Override
        public void onReceive(Context context, Intent intent) {
            // setMusicName();
            status = intent.getIntExtra(Constant.STATUS, 0);
//            Log.d(Config.TAG, "onReceive: " + status);
            current = intent.getIntExtra(Constant.KEY_CURRENT, 0);
            duration = intent.getIntExtra(Constant.KEY_DURATION, 100);
            currentSentence = intent.getStringExtra(Constant.KEY_CURRENT_SENTENCE);
            coverPic = intent.getStringExtra(Constant.KEY_PIC);
            // 存储歌词文件
            lrcContent = intent.getStringExtra(Constant.KEY_LRC_LIST);
            MyMusicUtil.setShared(Constant.KEY_LRC_LIST, lrcContent);

            switch (status) {
                case Constant.STATUS_STOP:
                    showPlayStatus(false);
                    flp_play_view.pause();
                    break;
                case Constant.STATUS_PLAY:
                    Log.e(Config.TAG, "收到Play Music --- SID >" + MyMusicUtil.getStringShared(Constant.KEY_ID));
                    MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(MyMusicUtil.getStringShared(Constant.KEY_ID));
                    if (musicDataByRid != null) {
                        if (musicDataByRid.getMenu().equals("我喜欢的音乐")) {
                            // 已经喜欢过该歌曲
                            // 置红色
                            fpm_like.setImageResource(R.drawable.ic_like_fill);
                        } else {
                            // 未喜欢过
                            fpm_like.setImageResource(R.drawable.ic_like_normal);
                        }
                    }
                    // 此处收到更新通知
                    ImageDownloader.downloadImageAsync(MyMusicUtil.getStringShared(Constant.KEY_PIC), bitmap -> {
                        if (!ObjectUtils.isEmpty(bitmap)) {
                            flp_play_view.setPlayPic(bitmap);
                        } else {
                            flp_play_view.setPlayPic(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo));
                        }
                        flp_play_view.play();
                    });
                    showPlayStatus(true);
                    flp_songname.setText(MyMusicUtil.getStringShared(Constant.KEY_NAME) + " - " + MyMusicUtil.getStringShared(Constant.KEY_SONGER));
                    // 设置封面图片
                    Glide.with(requireActivity()).load(MyMusicUtil.getStringShared(Constant.KEY_PIC)).placeholder(R.drawable.ic_logo).error(R.drawable.ic_logo).into(flp_cover_pic);
                    break;
                case Constant.STATUS_PAUSE:
                    showPlayStatus(false);
                    flp_play_view.pause();
                    break;
                case Constant.STATUS_RUN:
                    showPlayStatus(true);
                    fpm_progress.setMax(duration / 1000);
                    if (!isDraggingProgress) {
                        fpm_progress.setProgress(current / 1000);
                    }
                    if (fpm_lrcView.hasLrc()) {
                        fpm_lrcView.updateTime(current);
                    }
                    fpm_current_time.setText(TimeUtils.stampToDateS(current, "mm:ss"));
                    fpm_total_time.setText(TimeUtils.stampToDateS(duration, "mm:ss"));
                    break;
                case Constant.STATUS_LOAD_OK:
                    setLrcList(lrcContent);
                    MyMusicUtil.setShared(Constant.KEY_LRC_LIST, lrcContent);
                    fpm_title.setText(MyMusicUtil.getStringShared(Constant.KEY_NAME));
                    fpm_songer.setText(MyMusicUtil.getStringShared(Constant.KEY_SONGER));
                    MyMusicUtil.setShared(Constant.KEY_PIC, coverPic);
                    ImageDownloader.downloadImageAsync(MyMusicUtil.getStringShared(Constant.KEY_PIC), bitmap -> {
                        if (!ObjectUtils.isEmpty(bitmap)) {
                            flp_play_view.setPlayPic(bitmap);
                        } else {
                            flp_play_view.setPlayPic(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo));
                        }
                        flp_play_view.play();
                    });
                    break;
                case Constant.STATUS_REFRESH_LIKE_FROM_SEARCH_LIST:
                    MyMusicData musicDataBySid = SugarUtils.findMusicDataByRidOrSid(MyMusicUtil.getStringShared(Constant.KEY_ID));
                    if (musicDataBySid != null) {
                        if (musicDataBySid.getMenu().equals("我喜欢的音乐")) {
                            // 已经喜欢过该歌曲
                            // 置红色
                            fpm_like.setImageResource(R.drawable.ic_like_fill);
                        } else {
                            // 未喜欢过
                            fpm_like.setImageResource(R.drawable.ic_like_normal);
                        }
                    }
                    break;
                default:
                    break;
            }

        }

    }

    public void showPlayStatus(boolean isPlay) {
        fpm_play.setSelected(isPlay);
        if (isPlay) {
            flp_play_view.play();
        } else {
            flp_play_view.pause();
        }
        isStartPlayMusic = isPlay;
    }

    /**
     * 歌词点击监听
     *
     * @param view
     * @param time
     * @return
     */
    @Override
    public boolean onPlayClick(LrcView view, long time) {
        isDraggingProgress = false;
        Log.e(Config.TAG, "time： " + time);
        fpm_lrcView.updateTime(time);
        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PROGRESS);
        intent.putExtra(Constant.KEY_CURRENT, (int) time);
        requireActivity().sendBroadcast(intent);
        fpm_progress.setProgress((int) (time / 1000));
        isDraggingProgress = true;
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegister();
        unRegisterUpdateReceiver();
    }

    private void unRegister() {
        if (mReceiver != null) {
            requireActivity().unregisterReceiver(mReceiver);
        }
    }
}